﻿package net.wangit.user;

import java.util.HashMap;
import java.util.Map;

import net.wangit.Element;
import net.wangit.Row;
import net.wangit.framework.action.ActionMapping;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;


public class AdminUser extends RegisteredUser {

	private static final long serialVersionUID = 1L;
	private String administratorId;
	private static Map privateUnits;
	private static Map authorizationUnits;

	protected AdminUser(String id) {
		super(id);
	}

	protected void configure(Row row) {
		administratorId = row.get("adminid");
	}

	public boolean hasUnitPrivilege(String domain, String unitId,
			String unitShowMode) {
		return super.hasUnitPrivilege(domain, unitId, unitShowMode)
				|| isPrivateUnit(domain, unitId);
	}

	public boolean hasActionPrivilege(ActionMapping am) {
		return super.hasActionPrivilege(am)
				|| isPrivateUnit(am.getDomain(), am.getUnitId());
	}

	public boolean hasElementPrivilege(Element element) {
		if (super.hasElementPrivilege(element))
			return true;
		ElementComponent ec = (ElementComponent) element;
		if (ec.isAction()) {
			UnitComponent unit = ec.getParent();
			return isPrivateUnit(unit.getDomain(), unit.getId());
		} else {
			return false;
		}
	}

	public boolean hasDataPrivilege(Object key) {
		if (super.hasDataPrivilege(key)) {
			return true;
		} else {
			String params[] = StringUtil.split((String) key, ",");
			return isPrivateUnit(params[0], params[2]);
		}
	}

	private boolean isPrivateUnit(String domain, String unitId) {
		String unitKey = (new StringBuilder(String.valueOf(domain)))
				.append(",").append(unitId).toString();
		return privateUnits.containsKey(unitKey)
				|| authorizationUnits.containsKey(unitKey)
				&& isAuthorizationEnabled();
	}

	private boolean isAuthorizationEnabled() {
		if (!Checker.isEmpty(administratorId)) {
			Admin a = AdminFactory.getAdmin(administratorId);
			return a.isAuthorizationEnabled();
		} else {
			return false;
		}
	}

	public String getAdministratorId() {
		return administratorId;
	}

	static {
		privateUnits = new HashMap();
		authorizationUnits = new HashMap();
		privateUnits.put("app,user", null);
		privateUnits.put("app,user.query", null);
		privateUnits.put("app,user.list", null);
		privateUnits.put("app,user.form", null);
		privateUnits.put("adm,changepassword", null);
		authorizationUnits.put("adm,user.authorization", null);
	}
}
